using System;

namespace DebuggableInstallableService
{
    public static class ConsoleHarness
    {
        public static void Run(string[] args, IWindowsService service)
        {
            //string serviceName = service.GetType().Name;
            bool isRunning = true;

            service.OnStart(args);

            while (isRunning)
            {
                WriteToConsole(ConsoleColor.Yellow, "Enter either [Q]uit, [P]ause, [R]esume: ");
                isRunning = HandleConsoleInput(service, Console.ReadLine());
            }

            service.OnStop();
            service.OnShutdown();
        }

        private static bool HandleConsoleInput(IWindowsService service, string line)
        {
            bool canContinue = true;

            if (line != null)
            {
                switch (line.ToUpper())
                {
                    case "Q":
                        canContinue = false;
                        break;

                    case "P":
                        service.OnPause();
                        break;

                    case "R":
                        service.OnContinue();
                        break;

                    default:
                        WriteToConsole(ConsoleColor.Red, "Could understand input. Please try again!");
                        break;
                }
            }

            return canContinue;
        }

        private static void WriteToConsole(ConsoleColor color, string message, params object[] formatArguments)
        {
            ConsoleColor origCol = Console.ForegroundColor;
            Console.ForegroundColor = color;

            Console.WriteLine(message, formatArguments);
            Console.Out.Flush();

            Console.ForegroundColor = origCol;
        }
    }
}